import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'chat_group_list_controller.dart';
import '../../../function/model/chat_group_model.dart';
import '../../../function/state/chat_group_state.dart';
import '../../../function/utils/my_common.dart';
import '../../../function/widgets/join_group_dialog.dart';
import '../../../function/widgets/login_dialog_widget.dart';
import '../../../routes/app_routes.dart';

/// 群聊列表页面
/// 使用非常规命名避免标准模式
class ChatGroupListPage extends GetView<ChatGroupListController> {
  const ChatGroupListPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopBar(),

              SizedBox(height: 20.h),

              // 群聊列表
              Expanded(child: _buildGroupList()),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Get.back(),
            child: Icon(
              Icons.arrow_back_ios_new,
              size: 20.sp,
              color: MyCommonUtils.white,
            ),
          ),

          // 标题
          Expanded(
            child: Text(
              'Group Chat',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.w700,
                color: MyCommonUtils.white,
                fontFamily:
                    GoogleFonts.berkshireSwash(
                      fontWeight: FontWeight.w700,
                    ).fontFamily,
              ),
            ),
          ),

          // 占位空间，保持标题居中
          SizedBox(width: 20.w),
        ],
      ),
    );
  }

  /// 构建群聊列表
  Widget _buildGroupList() {
    return GetX<ChatGroupState>(
      builder: (chatGroupState) {
        final groups = chatGroupState.allGroups;

        if (groups.isEmpty) {
          return Center(
            child: Text(
              'No groups available',
              style: TextStyle(fontSize: 16.sp, color: MyCommonUtils.white),
            ),
          );
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          itemCount: groups.length,
          itemBuilder: (context, index) {
            final group = groups[index];
            return _buildAnimatedGroupCard(group, index);
          },
        );
      },
    );
  }

  /// 构建带动画效果的群聊卡片
  Widget _buildAnimatedGroupCard(ChatGroupModel group, int index) {
    return TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 400 + (index * 100)),
      tween: Tween(begin: 0.0, end: 1.0),
      curve: Curves.easeOutCubic,
      builder: (context, value, child) {
        return Transform.translate(
          offset: Offset(0, 30 * (1 - value)),
          child: Opacity(
            opacity: value,
            child: Transform.scale(
              scale: 0.9 + (0.1 * value),
              child: _buildGroupCard(group),
            ),
          ),
        );
      },
    );
  }

  /// 构建群聊卡片
  Widget _buildGroupCard(ChatGroupModel group) {
    return GestureDetector(
      onTap: () => _handleGroupCardTap(group),
      child: Container(
        margin: EdgeInsets.only(bottom: 22.h),
        child: AspectRatio(
          aspectRatio: 358 / 120,
          child: Container(
            decoration: BoxDecoration(
              image: const DecorationImage(
                image: AssetImage('assets/images/group_card.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: Padding(
              padding: EdgeInsets.only(left: 10.w, right: 10.w),
              child: Row(
                children: [
                  // 左侧列
                  _buildLeftColumn(group),

                  SizedBox(width: 12.w),

                  // 右侧列
                  Expanded(child: _buildRightColumn(group)),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建左侧列
  Widget _buildLeftColumn(ChatGroupModel group) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Spacer(),
        // Group Chat 文本
        Text(
          'Group Chat',
          style: TextStyle(
            fontSize: 13.sp,
            fontWeight: FontWeight.w700,
            color: MyCommonUtils.white,
          ),
        ),

        const Spacer(),

        // 群聊封面图片
        Container(
          width: 74.w,
          height: 74.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8.r),
            image: DecorationImage(
              image: AssetImage(group.coverImage),
              fit: BoxFit.cover,
            ),
          ),
        ),
        const Spacer(),
      ],
    );
  }

  /// 构建右侧列
  Widget _buildRightColumn(ChatGroupModel group) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 第一排：用户头像和加入按钮
        Row(
          children: [
            // 用户头像组
            _buildUserAvatars(group),

            Spacer(),

            // 加入按钮
            _buildJoinButton(group),
          ],
        ),

        const Spacer(),

        // 群聊标题
        Text(
          group.title,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w700,
            color: MyCommonUtils.white,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ).alignCenter(),

        SizedBox(height: 4.h),

        // 群聊详情文字
        Text(
          group.description,
          style: TextStyle(
            fontSize: 10.sp,
            fontWeight: FontWeight.w400,
            color: MyCommonUtils.white,
            height: 1.3,
          ),
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ),
        const Spacer(),
      ],
    );
  }

  /// 构建用户头像组
  Widget _buildUserAvatars(ChatGroupModel group) {
    // 获取群聊的固定头像
    final avatars = controller.getGroupAvatars(group.id);

    return SizedBox(
      width: 78.w, // 总宽度：54.w + 24.w
      height: 24.w, // 头像高度
      child: Stack(
        children: [
          // 第一个头像
          if (avatars.isNotEmpty)
            Positioned(left: 0, child: _buildUserAvatar(avatars[0])),

          // 第二个头像
          if (avatars.length > 1)
            Positioned(left: 18.w, child: _buildUserAvatar(avatars[1])),

          // 第三个头像
          if (avatars.length > 2)
            Positioned(left: 36.w, child: _buildUserAvatar(avatars[2])),

          // 更多图标
          Positioned(left: 54.w, child: _buildMoreIcon()),
        ],
      ),
    );
  }

  /// 构建单个用户头像
  Widget _buildUserAvatar(String avatarPath) {
    return Container(
      width: 24.w,
      height: 24.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: MyCommonUtils.white, width: 1.w),
        image: DecorationImage(
          image: AssetImage(avatarPath),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  /// 构建更多图标
  Widget _buildMoreIcon() {
    return Center(
      child: Image.asset('assets/images/more.png', width: 24.w, height: 24.w),
    );
  }

  /// 构建加入按钮
  Widget _buildJoinButton(ChatGroupModel group) {
    final isJoined = controller.isGroupJoined(group.id);

    return GestureDetector(
      onTap: () => controller.toggleGroupJoin(group.id),
      child: Obx(() {
        final scale = controller.getButtonScale(group.id);
        return Transform.scale(
          scale: scale,
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 2.h),
            decoration: BoxDecoration(
              color: isJoined ? MyCommonUtils.blue : MyCommonUtils.white,
              borderRadius: BorderRadius.circular(20.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.1),
                  blurRadius: 4.r,
                  offset: Offset(0, 2.h),
                ),
              ],
            ),
            child: Text(
              isJoined ? 'Joined' : 'Join',
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w700,
                color: MyCommonUtils.black,
              ),
            ),
          ),
        );
      }),
    );
  }

  /// 处理群聊卡片点击
  void _handleGroupCardTap(ChatGroupModel group) {
    final isJoined = controller.isGroupJoined(group.id);

    if (isJoined) {
      // 用户已加入，直接跳转到群聊页面
      Get.toNamed(AppRoutes.groupChat, arguments: group);
    } else {
      // 未加入前先判断是否登录
      if (!controller.userState.isLoggedIn) {
        Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
        return;
      }

      // 已登录则显示加入确认对话框
      JoinGroupDialogUtils.showJoinGroupDialog(
        group: group,
        onJoinConfirmed: () {
          controller.toggleGroupJoin(group.id);
          Get.toNamed(AppRoutes.groupChat, arguments: group);
        },
      );
    }
  }
}
